<!-- components/member-card-form.vue -->
<template>
  <view class="member-card-form">
    <view class="form-section">
      <view class="section-title">基本信息</view>
	  
	  <!-- 手机号 -->
	  <view class="form-item" :class="{ error: errors.phone }">
	    <view class="label">
	      <text class="label-text">手机号</text>
	      <text class="required">*</text>
	    </view>
	    <input
	      v-model="formData.phone"
	      class="form-input"
	      placeholder="请输入手机号码"
	      type="number"
	      maxlength="11"
	      @blur="validateField('phone')"
	    />
	    <view v-if="errors.phone" class="error-message">{{ errors.phone }}</view>
	  </view>
      
      <!-- 姓名 -->
      <view class="form-item" :class="{ error: errors.name }">
        <view class="label">
          <text class="label-text">姓名</text>
         <!-- <text class="required">*</text> -->
        </view>
        <input
          v-model="formData.name"
          class="form-input"
          placeholder="请输入真实姓名"
          maxlength="20"
          @blur="validateField('name')"
        />
        <view v-if="errors.name" class="error-message">{{ errors.name }}</view>
      </view>

      

      <!-- 生日 -->
     <!-- <view class="form-item" :class="{ error: errors.birthday }">
        <view class="label">
          <text class="label-text">生日</text>
          <text class="required">*</text>
        </view>
        <picker
          mode="date"
          :value="formData.birthday"
          :start="minDate"
          :end="maxDate"
          @change="onBirthdayChange"
        >
          <view class="picker" :class="{ placeholder: !formData.birthday }">
            {{ formData.birthday || '请选择生日' }}
          </view>
        </picker>
        <view v-if="errors.birthday" class="error-message">{{ errors.birthday }}</view>
      </view> -->

      <!-- 动态自定义字段 -->
      <view
        v-for="field in customFields"
        :key="field.name"
        class="form-item"
        :class="{ error: errors[field.name] }"
      >
        <view class="label">
          <text class="label-text">{{ field.label }}</text>
          <text v-if="field.required" class="required">*</text>
        </view>
        
        <!-- 文本输入 -->
        <input
          v-if="field.type === 'text'"
          v-model="formData[field.name]"
          class="form-input"
          :placeholder="`请输入${field.label}`"
          :maxlength="field.maxlength || 50"
          @blur="validateCustomField(field)"
        />
        
        <!-- 数字输入 -->
        <input
          v-else-if="field.type === 'number'"
          v-model="formData[field.name]"
          class="form-input"
          :placeholder="`请输入${field.label}`"
          type="number"
          @blur="validateCustomField(field)"
        />
        
        <!-- 选择器 -->
        <picker
          v-else-if="field.type === 'picker'"
          :value="formData[field.name]"
          :range="field.options"
          @change="(e) => onPickerChange(field.name, e)"
        >
          <view class="picker" :class="{ placeholder: !formData[field.name] }">
            {{ formData[field.name] || `请选择${field.label}` }}
          </view>
        </picker>
        
        <view v-if="errors[field.name]" class="error-message">
          {{ errors[field.name] }}
        </view>
      </view>
    </view>

    <!-- 协议 -->
    <view class="agreement-section">
      <label class="agreement-item">
        <checkbox
          :checked="agreed"
          @click="agreed = !agreed"
          color="#07C160"
        />
        <text class="agreement-text">
          我已阅读并同意
          <text class="link" @click="showAgreement">《会员服务协议》</text>
          和
          <text class="link" @click="showPrivacy">《隐私政策》</text>
        </text>
      </label>
    </view>
  </view>
</template>

<script>
import { validationRules, validate } from '@/utils/validate';

export default {
  name: 'MemberCardForm',
  props: {
    customFields: {
      type: Array,
      default: () => []
    },
    initialData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formData: {
        name: '',
        phone: '',
        birthday: '',
        ...this.initialData
      },
      errors: {},
      agreed: false,
      minDate: '1900-01-01',
      maxDate: this.getCurrentDate()
    };
  },
  methods: {
    getCurrentDate() {
      const now = new Date();
      return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
    },

    onBirthdayChange(e) {
      this.formData.birthday = e.detail.value;
      this.validateField('birthday');
    },

    onPickerChange(fieldName, e) {
      const value = e.detail.value;
      this.formData[fieldName] = this.customFields
        .find(f => f.name === fieldName)?.options[value] || '';
      this.validateCustomField({ name: fieldName });
    },

    validateField(fieldName) {
      const rules = validationRules[fieldName];
      if (!rules) return true;

      const value = this.formData[fieldName];
      for (const rule of rules) {
        if (!rule.validator(value)) {
          this.$set(this.errors, fieldName, rule.message);
          return false;
        }
      }

      this.$set(this.errors, fieldName, '');
      return true;
    },

    validateCustomField(field) {
      const value = this.formData[field.name];
      
      if (field.required && !validate.required(value)) {
        this.$set(this.errors, field.name, `${field.label}不能为空`);
        return false;
      }

      if (field.pattern && value) {
        const reg = new RegExp(field.pattern);
        if (!reg.test(value)) {
          this.$set(this.errors, field.name, field.errorMessage || '格式不正确');
          return false;
        }
      }

      this.$set(this.errors, field.name, '');
      return true;
    },

    validateAll() {
      let isValid = true;

      // 验证基础字段
      Object.keys(validationRules).forEach(field => {
        if (!this.validateField(field)) {
          isValid = false;
        }
      });

      // 验证自定义字段
      this.customFields.forEach(field => {
        if (!this.validateCustomField(field)) {
          isValid = false;
        }
      });

      // 验证协议
      if (!this.agreed) {
        uni.showToast({
          title: '请同意会员服务协议',
          icon: 'none'
        });
        isValid = false;
      }

      return isValid;
    },

    getFormData() {
      return { ...this.formData };
    },

    showAgreement() {
      uni.navigateTo({
        url: '/pages/common/webview?url=' + encodeURIComponent('/agreement/member')
      });
    },

    showPrivacy() {
      uni.navigateTo({
        url: '/pages/common/webview?url=' + encodeURIComponent('/agreement/privacy')
      });
    }
  }
};
</script>

<style scoped>
.member-card-form {
  padding: 0 30rpx;
}

.form-section {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-item {
  margin-bottom: 40rpx;
  position: relative;
}

.form-item.error {
  margin-bottom: 60rpx;
}

.label {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 32rpx;
  color: #333333;
}

.required {
  color: #ff4444;
  margin-left: 8rpx;
}

.form-input {
  height: 88rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 32rpx;
  background: #fafafa;
}

.form-input:focus {
  border-color: #07C160;
  background: #ffffff;
}

.form-item.error .form-input {
  border-color: #ff4444;
}

.picker {
  height: 88rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 32rpx;
  background: #fafafa;
  display: flex;
  align-items: center;
  color: #333333;
}

.picker.placeholder {
  color: #999999;
}

.error-message {
  position: absolute;
  bottom: -40rpx;
  left: 0;
  font-size: 24rpx;
  color: #ff4444;
}

.agreement-section {
  padding: 30rpx 0;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
}

.agreement-text {
  font-size: 28rpx;
  color: #666666;
  margin-left: 16rpx;
  line-height: 1.5;
}

.link {
  color: #07C160;
}
</style>